define([ './module' ], function(module) {
	'use strict';

	module.controller('order',serverorderctrl);
	function serverorderctrl($rootScope,$stateParams,$http,$location,$compile,$scope,DTOptionsBuilder,DTColumnBuilder,Upload,$timeout,GoodsTypeService) {
		$scope.title="添加订单";

		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		setDtOptions();
		setResultData();
		/**
		 * 设置网络请求
		 */
		function setDtOptions(){
			vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
					type:'POST',
					url:'../mall/products/findProductByPage',
					dataSrc:'data'
				})
				.withOption('processing',true)
				.withOption('paging',true)
				.withOption('serverSide',true)
				.withOption('createdRow',function(row,data,dataIndex){
					$compile(angular.element(row).contents())($scope);
				})
				.withOption('headerCallback', function(header) {
					if (!$scope.headerCompiled) {
						$scope.headerCompiled = true;
						$compile(angular.element(header).contents())($scope);
					}
				})
				.withOption('stateSave', true)
				.withOption('rowCallback',rowCallback)
				.withPaginationType('full_numbers')
				.withLanguageSource('./app/language/chinese.json')

			$scope.$on('handleRequest',function(){

			});
		}

		/**
		 * 设置数据回调渲染
		 * @param imgHtml
		 */
		function setResultData(){
			var titleHtml='<input type="checkbox" ng-model="gt.selectAll" ng-click="gt.toggleAll(gt.selectAll,gt.selected)">';
			vm.dtColumns=[
				DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
					vm.selected[full.id]=false;
					return "<input type='checkbox' ng-model=\"gt.selected['"+data.id+"']\" ng-click=\"gt.toggleOne(gt.selected)\">";
				}),
				DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
				DTColumnBuilder.newColumn(null).withTitle('图片').notSortable().renderWith(imgHtml),
				DTColumnBuilder.newColumn('psn').withTitle('货号').notSortable(),
				DTColumnBuilder.newColumn('productname').withTitle('货物名称').notSortable(),
				DTColumnBuilder.newColumn('nname').withTitle('分类').notSortable(),
				DTColumnBuilder.newColumn('goodstypename').withTitle('商品类型').notSortable(),
				DTColumnBuilder.newColumn('stock').withTitle('库存').notSortable(),
				DTColumnBuilder.newColumn('saleprice').withTitle('销售价').notSortable(),
				DTColumnBuilder.newColumn('memberprice').withTitle('会员价').notSortable(),
				DTColumnBuilder.newColumn('salestatus').withTitle('销售状态').notSortable(),
				DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
				DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable()];
			function imgHtml(data,type,full,meta){
				return '<img style="width:50px;height:50px;" ng-src="'+data.mainimg+'" alt="Photo" />';
			}
		}
		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:'',
				psn:'',
				goodstypeid:''
			};
			if($scope.productname!=undefined){
				searchParams.name=$scope.productname;

			}
			if($scope.psn!=undefined){
				searchParams.psn=$scope.psn;
			}
			if($scope.selectedgoodstype.goodstypeid!=undefined){
				searchParams.goodstypeid=$scope.selectedgoodstype.goodstypeid;
			}else{
				$scope.errors = {
					show: true,
					msg: '请选择商品类型'
				}
				return false;
			}
			vm.dtOptions['ajax'].data=searchParams;
			vm.dtInstance.reloadData(resetPaging);
		}



		/**
		 * 表格搜索
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;

		}

		function someClickHandler(info) {
			vm.message = info.id + ' - ' + info.name;
			$scope.pushToSelectedProducts(info.id,info);
		}
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
			$('td', nRow).bind('click', function() {
				$scope.$apply(function() {
					vm.someClickHandler(aData);
				});
			});
			return nRow;
		}

		//选定货物
		$scope.sp = [];
		$scope.pushToSelectedProducts = function (index, product) {
			var tag=true;
			angular.forEach($scope.sp,function(d){
				if(d.id==product.id){
					alert("该商品已经存在");
					tag=false;
				}

			});
			if(tag){
				$scope.sp.push(product);
			}
			$scope.selectedproducts = $scope.sp;
		};

		/**
		 * 删除选择的货物
		 * @param index
		 */
		$scope.removeselectproduct=function(index){
			$scope.selectedproducts.splice(index,1);
		}


		//查询所有商品类型
		$scope.findallgoodstype = function () {
			var promise = GoodsTypeService.query();
			promise.then(function (data) {
				$scope.goodstypeselect = data.beanlist;
			}, function (data) {
				$scope.errors = {
					show: true,
					msg: '系统异常'
				}
			});
		};

		/**
		 * 搜索物流商信息
		 */
		$scope.filterLogisticsBusiness=function(){
			$http({
				method:'POST',
				url:'../mall/logisticsbusiness/findAll'
			}).success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.errors={};
					$scope.logisticslists=data.beanlist;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}

		/**
		 * 搜索支付方式
		 */
		$scope.filterPayment=function(){
			$http({
				method:'POST',
				url:'../mall/payment/findAll'
			}).success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.errors={};
					$scope.paymentlist=data.beanlist;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}





		/**
		 * 搜索会员的收获地址信息和开票信息
		 */
		$scope.filterSearchMemberDeliveraddressAndInvoice=function(){
			if($scope.mobile==undefined){
				$scope.errors={
						show:true,
						msg:'请输入会员的手机号进行搜索'
				}
				return false;
			}

			$http({
				method:'POST',
				url:'../mall/memberdeliveraddress/filterMemberDeliverAddress',
				data:{
					'mobile':$scope.mobile
				}
			}).success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.errors={};
					$scope.memberdeliveraddresssearchresult=data.beanlist;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
					show:true,
					msg:'系统异常'
				}
			});

			$http({
				method:'POST',
				url:'../mall/memberinvoice/filterMemberInvoice',
				data:{
					'mobile':$scope.mobile
				}
			}).success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.errors={};
					$scope.memberinvoicesearchresult=data.beanlist;
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
						show:true,
						msg:'系统异常'
				}
			});
		}


		//选定的收获地址

		$scope.pushToSelectedMemberDeliveraddress=function(index,md){
			var mda=[];
			mda.push(md);
			$scope.selectedmda=mda;
		};

		$scope.removeSelectedMemberDeliveraddress=function(index){
			$scope.selectedmda.splice(index,1);
		}

		//选定发票信息

		$scope.pushToSelectedMemberInvoice=function(index,m){
			var mi=[];
			mi.push(m);
			$scope.selectedmi=mi;
		};

		$scope.removeSelectedMemberInvoice=function(index){
			$scope.selectedmi.splice(index,1);
		}

		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate||$stateParams.operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			$scope.title='添加订单';

			$scope.watchlogistics=function(id){
				$scope.logisticsid=id;
				console.log($scope.logisticsid);
			}

			$scope.watchpayment=function(id){
				$scope.paymentid=id;
				console.log($scope.paymentid);
			}

			$scope.save=function(){
				var selectOrderProducts="";
				if($scope.selectedproducts==undefined){
					$scope.errors={
							show:true,
							msg:'请选择订单货物'
					}
					return false;
				}else{
					var temparray=[];
					angular.forEach($scope.selectedproducts,function(d,i,a){
							temparray.push(d.id);
					});
					selectOrderProducts=temparray.join(",");
				}
				if($scope.mobile==undefined){
					$scope.errors={
							show:true,
							msg:'请输入会员手机号进行搜索开票和地址信息'
					}
					return false;
				}

				var memberaddressid="";
				if($scope.selectedmda==undefined){
					$scope.errors={
							show:true,
							msg:'请选择订单收获地址'
					}
					return false;
				}else{
					angular.forEach($scope.selectedmda,function(d,i,a){
						memberaddressid=d.id;
					});
				}

				var memberinvoiceid="";
				if($scope.selectedmi==undefined){
					$scope.errors={
							show:true,
							msg:'请选择订单发票'
					}
					return false;
				}else{
					angular.forEach($scope.selectedmi,function(d,i,a){
						memberinvoiceid=d.id;
					});
				}

				if($scope.logisticsid==undefined){
					$scope.errors={
							show:true,
							msg:'请选择物流商'
					}
					return false;
				}

				if($scope.paymentid==undefined){
					$scope.errors={
							show:true,
							msg:'请选择支付方式'
					}
					return false;
				}

				if($scope.freight==undefined){
					$scope.errors={
							show:true,
							msg:'请输入订单运费'
					}
					return false;
				}
				if($scope.shouldpay==undefined){
					$scope.errors={
							show:true,
							msg:'请输入订单总价'
					}
					return false;
				}

				$http({
					method:'POST',
					url:'../mall/order/saveBackOrder',
					data:{
						"selectproducts":selectOrderProducts,
						"mobile":$scope.mobile,
						"memberdeliveraddressid":memberaddressid,
						"memberinvoiceid":memberinvoiceid,
						"logisticsid":$scope.logisticsid,
						"paymentid":$scope.paymentid,
						"freight":$scope.freight,
						"shouldpay":$scope.shouldpay
					}
				})
				.success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'订单添加成功'
						}
						$location.path('/orderment');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

			}
		}


	}

	//
	//
	//
    //


	//ordermodule.controller('orderment',ServerGoodsmentCtrl);
	////查询列表数据
	//function ServerGoodsmentCtrl($http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
	//	var vm=this;
	//	vm.message='';
	//	vm.someClickHandler = someClickHandler;
	//	vm.selected={};
	//	vm.selectAll=false;
	//	vm.toggleAll=toggleAll;
	//	vm.toggleOne=toggleOne;
	//	vm.dtInstance={};
	//	var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
	//	vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
	//		type:'POST',
	//		url:'../mall/goods/findByPage.action',
	//		dataSrc:'data'
	//	})
	//	.withOption('processing',true)
	//	.withOption('paging',true)
	//	.withOption('serverSide',true)
	//	.withOption('createdRow',function(row,data,dataIndex){
	//		$compile(angular.element(row).contents())($scope);
	//	})
	//	.withOption('headerCallback', function(header) {
     //       if (!$scope.headerCompiled) {
     //           $scope.headerCompiled = true;
     //           $compile(angular.element(header).contents())($scope);
     //       }
     //   })
     //   .withOption('stateSave', true)
     //   .withOption('rowCallback',rowCallback)
	//	.withPaginationType('full_numbers')
	//	.withLanguageSource('./app/language/chinese.json')
    //
	//	$scope.$on('handleRequest',function(){
    //
	//	});
	//	vm.dtColumns=[
	//	              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
	//	            	  vm.selected[full.id]=false;
	//	            	  return "<input type='checkbox' ng-model=\"showCase.selected['"+data.id+"']\" ng-click=\"showCase.toggleOne(showCase.selected)\">";
	//	              }),
	//	              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
	//	              DTColumnBuilder.newColumn(null).withTitle('图片').notSortable().renderWith(imgHtml),
	//
	//		          DTColumnBuilder.newColumn('goodsname').withTitle('商品标题').notSortable(),
	//		          DTColumnBuilder.newColumn('subgoodsname').withTitle('副标题').notSortable(),
	//		          DTColumnBuilder.newColumn('nname').withTitle('分类').notSortable(),
	//		          DTColumnBuilder.newColumn('goodstypename').withTitle('商品类型').notSortable(),
	//		          DTColumnBuilder.newColumn('price').withTitle('价格').notSortable(),
	//		        	DTColumnBuilder.newColumn('msync').withTitle('移动端状态').notSortable(),
	//		          DTColumnBuilder.newColumn('sort').withTitle('排序').notSortable(),
	//		          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
	//		          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
	//		          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
	//		          DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];
	//	function imgHtml(data,type,full,meta){
	//		return '<img style="width:50px;height:50px;" ng-src="'+data.smainimg+'" alt="Photo" />';
	//	}
	//	function actionHtml(data,type,full,meta){
	//		return "<button  ng-click=\"edit('"+data.id+"')\" class='btn btn-warning'><i class='fa fa-edit'></i></button>";
	//	}
    //
	//	function reloadData(){
	//		var resetPaging = false;
	//        vm.dtInstance.reloadData(callback, resetPaging);
	//	}
	//	function callback(data){
	//	}
    //
    //
	//	//表格中编辑按钮
	//	$scope.edit=function(id,name){
	//		$location.path('/goods').search({'operate':'edit','id':id});
	//	}
	//
	//
    //
	//	/**
	//	 * 跳转到添加商品类型和参数页面
	//	 */
	//	$scope.save=function(){
	//		$location.path('/goods').search({'operate':'save'});
	//	}
    //
	//	$scope.del=function(){
	//		var i=0;
	//		var ids=[];
	//		angular.forEach(vm.selected, function(data,index,array){
	//			if(data){
	//				i++;
	//				ids.push(index);
	//			}
	//		});
	//		if(i==0){
	//			$scope.errors={
	//					show:true,
	//					msg:'请选择一条记录'
	//			}
	//		}else{
	//			$scope.errors={
	//					show:false
	//			}
	//			//批量删除数据
	//			var idstrs=ids.join(",");
	//			$http({
	//				method:'POST',
	//				url:'../mall/goods/del.action',
	//				data:{
	//					'ids':idstrs
	//				}
	//			}).
	//			success(function(data,status,headers,config){
	//				if(data.sucflag){
	//					$scope.errors={};
	//					$scope.info={
	//							show:true,
	//							msg:'删除成功'
	//					}
	//					reloadData();
	//				}
    //
	//			}).
	//			error(function(data,status,headers,config){
	//				$scope.errors={
	//						show:true,
	//						msg:'系统异常'
	//				}
	//			});
	//		}
	//	}
    //
	//	/**
	//	 * 列表全选
	//	 */
	//	function toggleAll(selectAll,selectedItems){
	//		for(var id in selectedItems){
	//			if(selectedItems.hasOwnProperty(id)){
	//				selectedItems[id]=selectAll;
	//			}
	//		}
	//	}
	//	/**
	//	 * 列表单选
	//	 */
	//	function toggleOne(selectedItems){
	//		var me=this;
	//		for(var id in selectedItems){
	//			if(selectedItems.hasOwnProperty(id)){
	//				if(!selectedItems[id]){
	//					me.selectAll=false;
	//				}
	//			}
	//		}
	//		me.selectAll=true;
	//	}
    //
	//	function someClickHandler(info) {
	//        vm.message = info.id + ' - ' + info.name;
	//    }
	//	/**
	//	 * 单击列表某行回调
	//	 */
	//	function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
	//		$('td', nRow).unbind('click');
	//        $('td', nRow).bind('click', function() {
	//            $scope.$apply(function() {
	//                vm.someClickHandler(aData);
	//            });
	//        });
	//        return nRow;
	//	}
    //
	//}
});
